package cn.edu.tyu.finance.thingstype.servlet;

import cn.edu.tyu.finance.thingstype.domain.Users;
import cn.edu.tyu.finance.thingstype.service.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "UserServlet", value = "/UserServlet")
public class UserServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String method = request.getParameter("method");
        if ("add".equals(method)) {
            addUser(request,response);
        }
    }
    private void addUser(HttpServletRequest request, HttpServletResponse response) {
        //接受页面发送过来的参数
        String userid = request.getParameter("userid");
        String username = request.getParameter("username");
        String userpsw = request.getParameter("userpsw");
        Users users = new Users();
        users.setUseid(userid);
        users.setUsename(username);
        users.setUserpsw(userpsw);
        UserServiceImpl userServiceImpl = new UserServiceImpl();
        int res=0;
        try {
            res = userServiceImpl.addUser(users);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (res>0) {
            //进入查询页面
            try {
                response.sendRedirect(request.getContextPath()+"/user?method=queryUser");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }else{
            //还是在添加页面
            try {
                response.sendRedirect(request.getContextPath()+"/addUser.jsp");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
